const db = require('../../db/index')
const { isUrl } = require('../../utils/util')
const APP_CONFIG = require('../../utils/config')

// START TRANSACTION;
// insert into articles(articleTitle,articleContent,cates,tags,publicUserId,articleCover) values('12313','文章的内容创作','1,2,3,4','1,2,3',10,'http://baidu.com');
// SET @arts_id = LAST_INSERT_ID();
// UPDATE cates t set t.cateArticles = CONCAT_WS(',',t.cateArticles,@arts_id) WHERE t.cateId IN (TRIM(BOTH "''" FROM '1,2,3,4'))
// ROLLBACK;


/* 插入文章 插入成功之后需要将当前的文章标签，分类插入 */
exports.createArticle = (req, res) => {
    let { articleTitle, articleContent, cates, tags, articleCover, articleDesc, isLock, articlePassword } = req.body;

    // 校验必传参数
    if (articleContent && articleTitle && cates && tags && articleDesc) {
        // 处理 articleCover
        articleCover = articleCover ? articleCover.replace(/\\/g, '/') : 'upload/default_cover.jpg';

        // SQL 参数准备
        let sqlParams = [articleTitle, articleContent, cates, tags, req.uid, articleCover, articleDesc, cates, tags];

        // 插入文章的 SQL
        let insertSql =
            "START TRANSACTION;" +
            "INSERT INTO articles(articleTitle, articleContent, cates, tags, publicUserId, articleCover, articleDesc) " +
            "VALUES(?,?,?,?,?,?,?);" +
            "SET @arts_id = LAST_INSERT_ID();" +
            "UPDATE cates t SET t.cateArticles = IF(t.cateArticles IS NULL OR t.cateArticles = '', @arts_id, TRIM(',' FROM CONCAT_WS(',', t.cateArticles, @arts_id))) WHERE FIND_IN_SET(t.cateId, ?) > 0;" +
            "UPDATE tags tg SET tg.tagArticles = IF(tg.tagArticles IS NULL OR tg.tagArticles = '', @arts_id, TRIM(',' FROM CONCAT_WS(',', tg.tagArticles, @arts_id))) WHERE FIND_IN_SET(tg.tagId, ?) > 0;";

        // 如果传递了 isLock 和 articlePassword，更新相应字段
        if (isLock !== undefined || articlePassword) {
            insertSql += " UPDATE articles SET ";

            // 如果 isLock 被传递，更新 isLock 字段
            if (isLock !== undefined) {
                insertSql += "isLock = ?, ";
                sqlParams.push(isLock);
            }

            // 如果 articlePassword 被传递，更新 articlePassword 字段
            if (articlePassword) {
                if(!isLock || isLock == undefined || isLock==0) {

                }else {
                    articlePassword = Buffer.from(articlePassword+APP_CONFIG.privateKey,'utf8').toString('base64')
                    insertSql += "articlePassword = ?, ";
                    sqlParams.push(articlePassword);
                }
            }

            // 去掉多余的逗号，并设置 WHERE 条件
            insertSql = insertSql.slice(0, -2); // 删除最后一个逗号
            insertSql += " WHERE articleId = @arts_id;";
        }

        // 完成事务，处理查询
        insertSql += "COMMIT;";

        db.query(insertSql, sqlParams, (err, result) => {
            if (err) {
                console.log('添加文章失败', err);
                res.send({
                    code: 400,
                    message: '添加文章失败'
                });
                return;
            } else {
                res.send({
                    code: 200,
                    message: '添加文章成功'
                });
                return;
            }
        });
    } else {
        res.send({
            code: 400,
            message: '请检查参数是否正确'
        });
        return;
    }
};

// 删除文章 拿到当前 uid检测是否是本人 是的话可以删 不是的话检测是否是管理员 是管理也可以删除

exports.deleteArticle = (req, res) => {
    let { articleId } = req.params
    let { uid } = req
    //     查询当前uid的信息
    if (uid && articleId) {
        let selectUserInfoSql = "select userType from users where userId = ?"
        db.query(selectUserInfoSql, [uid], (err, result) => {
            if (err) {
                res.send({
                    code: 400,
                    message: err.sqlMessage
                })
                return
            } else {
                console.log('reslut', result)
                let { userType } = result[0]
                // 说明不是管理员 去验证一下是否为当前用户本人操作
                if (userType == 0) {
                    let checkSql = "select publicUserId from articles where articleId = ?"
                    db.query(checkSql, [articleId], (error, response) => {
                        if (error) {
                            res.send({
                                code: 400,
                                message: error.sqlMessage
                            })
                            return
                        }
                        console.log('response', response,)
                        if (response.length == 0) {
                            res.send({
                                code: 400,
                                message: '文章不存在',
                            })
                            return
                        }
                        let { publicUserId } = response[0]
                        // 说明是用户本人的操作
                        if (publicUserId == uid) {
                            deleteArticleHandler(articleId, req, res)
                            return
                        }
                        res.send({
                            code: 400,
                            message: '你无权删除本篇文章'
                        })
                        return;
                    })
                } else if (userType == 1) {
                    //     说明是管理员可以执行删除操作了
                    deleteArticleHandler(articleId, req, res)
                }
            }
        })
    } else {
        res.send({
            code: 400,
            message: '操作失败,请检查参数是否正确'
        })
        return
    }
}

/**
 * @description 删除文章处理函数
 * */
function deleteArticleHandler(articleId, req, res) {
    let deletSql = "delete from articles where articleId = ?"
    db.query(deletSql, [articleId], (error, result) => {
        if (error) {
            res.send({
                code: 400,
                message: error.sqlMessage
            })
            return
        }
        if (result.length == 0) {
            res.send({
                code: 400,
                message: '文章不存在'
            })
            return;
        }
        res.send({
            code: 200,
            message: '删除成功'
        })
        return;
    })
}


/*获取文章的详情*/
exports.getArticle = (req, res) => {
    let { articleId } = req.params
    console.log('读取的文章id', articleId)
    if (articleId) {
        let getSql = 'select articleId,articleTitle,articleContent,publicTime,publicUserId,likeCount,viewsCount,cates,tags,articleCover,articleDesc,isLock from articles where articleId = ?'
        db.query(getSql, [articleId], (error, result) => {
            if (error) {
                res.send({
                    code: 400,
                    message: error.sqlMessage
                })
                return
            }
            if (result.length == 0) {
                res.send({
                    code: 200,
                    message: '所查看的文章已经不在了,请浏览其他文章'
                })
                return
            }
            // 查询当前的文章成功 查询获取文章的相关信息
            let selectSql = "SELECT articleId,articleTitle,articleContent,publicTime,likeCount,repliesCount,viewsCount,isLock,articleCover,cates,tags,userIp,userParty,userEmail,userAvatar,userType from articles JOIN users ON userId = ? WHERE articleId = ? "
            db.query(selectSql, [result[0].publicUserId, articleId], (error, response) => {
                if (error) {
                    res.send({
                        code: 400,
                        message: error.sqlMessage || '获取文章相关信息失败',
                    })
                    return
                }
                //     查询成功相关的信息
                if (response) {
                    // 查询当前文章的分类信息
                    response[0].articleCover = isUrl(response[0].articleCover) ? response[0].articleCover : APP_CONFIG.imagePrefixe + response[0].articleCover
                    console.log('文章详情---?' , response[0])
                    findArticleCate(response[0], req, res)
                }
                return;
            })
        })
    }
}

// 查询当前分类下面的所有文章   // SELECT * FROM `articles` JOIN `cates` as b WHERE articleId in (b.cateArticles)

function findArticleCate(response, req, res) {
    let { cates } = response // 分类字符串
    console.log(cates)
    let findSql = `SELECT cateId,cateName,cateAlias,cateDesc,cateParentId from cates WHERE cateId in (${cates})`
    db.query(findSql, (err, result) => {
        console.log(findSql)
        if (err) {
            res.send({
                code: 400,
                message: err.sqlMessage
            })
            return
        }
        console.log(result)
        response["cates"] = result
        findArticleTags(response, req, res)
    })
}


// 查询文章的标签
function findArticleTags(response, req, res) {
    let { tags } = response
    let findTagsSql = `SELECT * from tags WHERE tagId in (${tags})`
    db.query(findTagsSql, (err, result) => {
        if (err) {
            res.send({
                code: 400,
                message: err.sqlMessage
            })
            return
        }
        response["tags"] = result
        res.send({
            code: 200,
            message: '获取文章信息成功',
            articleInfo: response
        })
    })
}

/*对比文章的密码是否相同 对比的话使用base64加解秘 然后采用加密方式为 '密码'+ '固定私钥' = base64 */
exports.checkArticlePwd = (req, res) => {
    let { articleId, articlePwd } = req.query
    if (articleId && articlePwd) {
        let getSql = 'select articlePassword from articles where articleId = ?'
        db.query(getSql, [articleId], (error, result) => {
            if (error) {
                res.send({
                    code: 400,
                    message: error.sqlMessage
                })
                return;
            }
            if (result.length == 0) {
                res.send({
                    code: 400,
                    message: '文章不存在'
                })
                return
            }
            // 对比传递过来的和数据库是否相同
            articlePwd = Buffer.from(articlePwd+APP_CONFIG.privateKey, 'utf8').toString('base64')
            console.log(result[0], articlePwd)
            if (result[0].articlePassword == articlePwd || result[0].articlePassword==null) {
                res.send({
                    code: 200,
                    message: '密码正确'
                })
                return;
            }else {
                res.send({
                    code: 400,
                    message: '密码错误'
                })
            }
        })
    }
}

// 查询当前文章 并且上一篇和下一篇
exports.getCurrentArticleContext = (req, res) => {
    let { articleId } = req.query
    articleId = articleId * 1
    let findArticleSql = `
        SELECT *
        FROM (
        SELECT * 
        FROM articles 
        WHERE articleId < ${articleId}  
        ORDER BY articleId DESC 
        LIMIT 1
        ) AS prev_article
        UNION ALL
        SELECT *
        FROM (
        SELECT * 
        FROM articles 
        WHERE articleId > ${articleId} 
        ORDER BY articleId ASC 
        LIMIT 1
        ) AS next_article;
    `
    db.query(findArticleSql, (err, result) => {
        console.log(err);
        if (err) return res.send({ code: 400, message: err.sqlMessage })
        // console.log('文章的上下文', result);
        res.send({ code: 200, message: '查询上下文成功', prevArticle: result[1], nextArticle: result[0] })
    })
}

/* 获取热门文章列表 */
exports.getHostArticleList = (req, res) => {
    let count = req.count || 5
    let findSql = "SELECT * FROM articles ORDER BY CAST(likeCount AS UNSIGNED) DESC LIMIT 0, ?"
    db.query(findSql,count,(err,result) => {
        if(err) return res.send({ code: 400, message: err.sqlMessage })
        res.send({ code: 200, message: '查询热门文章成功', hostList: result })
    })
}

// 更新文章的阅读量
exports.updateArticleViews = (req,res) => {
    let articleId = req.params.articleId
    let updateSql = "UPDATE articles SET viewsCount = viewsCount + 1 WHERE articleId = ?"
    db.query(updateSql,articleId,(err,result) => {
        if(err) return res.send({ code: 400, message: err.sqlMessage })
        res.send({ code: 200, message: '更新阅读量成功'})
    })
}

// 更新文章的点赞量
exports.updateArticleLikes = (req,res) => {
    let articleId = req.params.articleId
    let updateSql = "UPDATE articles SET likeCount = likeCount + 1 WHERE articleId = ?"
    db.query(updateSql,articleId,(err,result) => {
        if(err) return res.send({ code: 400, message: err.sqlMessage })
        res.send({ code: 200, message: '更新点赞量成功' })
    })
}

// 返回对应文章的数据库信息
const findArticleInfo = (articleId) => {
    return new Promise((resolve,reject) => {
        let findSql = "SELECT * FROM articles WHERE articleId = ?"
        db.query(findSql,articleId,(err,result) => {
            if(err) return reject(err)
            resolve(result[0])
        })
    })
}


// 管理员修改对应的文章信息
exports.updateArticleInfo = (req,res) => {
    let articleId = req.params.articleId // 获取文章id
    let {articleTitle,articleContent,articleCover,articleDesc,publicTime,likeCount,repliesCount,viewsCount,tags,cates,} = req.body // 获取传递的信息 有的话进行使用
    let updateSql = "UPDATE articles SET articleTitle = ?,articleContent = ?,articleCover = ?,articleDesc = ?,publicTime = ?,likeCount = ?,repliesCount = ?,viewsCount = ?,tags = ?,cates = ? WHERE articleId = ?"
    let findResultInfo = null
    findArticleInfo(articleId).then(result => {
        findResultInfo = result
        db.query(updateSql,[articleTitle || findResultInfo.articleTitle,articleContent || findResultInfo.articleContent,articleCover || findResultInfo.articleCover,articleDesc || findResultInfo.articleDesc,publicTime || findResultInfo.publicTime,likeCount || findResultInfo.likeCount,repliesCount || findResultInfo.repliesCount,viewsCount || findResultInfo.viewsCount,tags || findResultInfo.tags,cates || findResultInfo.cates,articleId],(sqlerr,sqlResult) => {
            if(sqlerr) return res.send({ code: 400, message: '修改失败',errorMessage:sqlerr })
            res.send({ code: 200, message: '修改成功' })
        })
    }).catch(err => {
        res.send({ code: 400, message: '没有查询到当前文章' })
    })
}